import sqlite3

# 连接到数据库
conn = sqlite3.connect('./openmemory.db')
cursor = conn.cursor()

print("=== 检查n8n相关状态 ===")

# 1. 检查所有应用
cursor.execute("SELECT id, name, created_at FROM apps")
all_apps = cursor.fetchall()
print(f"\n1. 发现 {len(all_apps)} 个应用:")
for app in all_apps:
    cursor.execute("SELECT COUNT(*) FROM memories WHERE app_id = ?", (app[0],))
    count = cursor.fetchone()[0]
    print(f"   - ID: {app[0]}")
    print(f"   - 名称: {app[1]}")
    print(f"   - 创建时间: {app[2]}")
    print(f"   - 记忆数量: {count}")
    print()

# 2. 检查特定用户ID的记忆
cursor.execute("""
    SELECT a.id, a.name, COUNT(m.id) as memory_count
    FROM apps a
    LEFT JOIN memories m ON a.id = m.app_id
    GROUP BY a.id, a.name
    ORDER BY memory_count DESC
""")
memory_distribution = cursor.fetchall()
print(f"\n2. 记忆分布:")
for app_id, app_name, count in memory_distribution:
    print(f"   {app_name} (ID: {app_id}): {count} 条记忆")

# 3. 检查是否有重复的应用名称
cursor.execute("""
    SELECT name, COUNT(*) as count
    FROM apps
    GROUP BY name
    HAVING COUNT(*) > 1
""")
duplicates = cursor.fetchall()
print(f"\n3. 重复应用名称:")
if duplicates:
    for name, count in duplicates:
        print(f"   {name}: {count} 个实例")
else:
    print("   无重复应用名称")

# 4. 检查所有记忆的总数
cursor.execute("SELECT COUNT(*) FROM memories")
total_memories = cursor.fetchone()[0]
print(f"\n4. 总记忆数量: {total_memories}")

conn.close()

print("\n=== 检查完成 ===")